package com.itlxd.handler;

import com.itlxd.exception.*;
import com.itlxd.result.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author: lixiaodong
 **/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public ResultVO<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return ResultVO.error(msg);
        }
        log.info(ex.getMessage());
        return ResultVO.error("未知错误");
    }

    /**
     * 自定义异常处理器
     * @param e
     * @return
     */
    @ExceptionHandler({ArgsException.class, LoginException.class, CategoryException.class, SqlOperationException.class,
            SetmealException.class})
    public ResultVO ArgsExceptionHandler(Exception e) {
        return ResultVO.error(e.getMessage());
    }
}
